﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using moc.Common;
using moc.IBLL;
using moc.IDAL;
using moc.Models;

namespace moc.BLL
{
    public class ProductInfoBll :BaseBll,IProductInfoBll
    {
        private readonly IProductInfoDal _dal;
        private readonly IProductCommentDal _comdal;
        public ProductInfoBll(IUnitOfWork unitOfWork,IProductInfoDal dal,IProductCommentDal comdal) : base(unitOfWork)
        {
            _dal = dal;
            _comdal = comdal;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public bool AddProduct(ProductInfo product)
        {
            _dal.Add(product);
            return (_unitOfWork.SaveChanges() > 0);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public bool DeleteProduct(List<ProductInfo> product)
        {
            _dal.Delete(product);
            List<ProductComment> comment = new List<ProductComment>();
            foreach (var item in product)
            {
                comment.Add(new ProductComment() { Product_id = item.Product_id });
            }
            _comdal.Delete(comment);
            return (_unitOfWork.SaveChanges() > 0);
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IQueryable<ProductInfo> GetProductInfo(Guid id)
        {
            return _dal.LoadEntities(p => p.Product_id == id);
        }

        /// <summary>
        /// 获取商品分页
        /// </summary>
        /// <param name="page"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public IQueryable<ProductInfo> LoadPage(PageParam page, out int total)
        {
            IQueryable<ProductInfo> pageData;
            switch (page.Sort)
            {
                case nameof(ProductInfo.Product_name):
                    pageData = _dal.LoadPage(page.PageSize, page.PageIndex, out total, u => u.Product_name == page.SearchText, u => u.Product_name, page.Order);
                    break;
                default:
                    pageData = _dal.LoadPage(page.PageSize, page.PageIndex, out total, u => u.Product_name == page.SearchText, u => u.Product_id, page.Order);
                    break;
            }
            return pageData;
        }

        /// <summary>
        /// 修改商品详情
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public bool Update(ProductInfo product)
        {
            _dal.Update(product);
            return (_unitOfWork.SaveChanges() > 0);
        }
    }
}
